import Access from '@/components/Access';
import type { ProColumns } from '@/components/Pro';
import { ProTable } from '@/components/Pro';
import Tabs from '@/components/Tabs';
import { monitorServerControllerServerPage } from '@/services/ess/alertConfig';
import { Space } from 'antd';
import { parse } from 'querystring';
import React, { useState } from 'react';
import { Link, useIntl, useLocation } from 'umi';
import PackageMang from '../EmsComponentManagement/PackageMang';
import AlarmConfig from './components/AlarmConfig';
import AlarmHistory from './components/AlarmHistory';
import BaseInfo from './components/BaseInfo';
import styles from './index.less';

interface StatusListProps {
  stationId: number;
  onDetailsClick: (serverId: number) => void;
}

const StatusList: React.FC<StatusListProps> = ({ stationId, onDetailsClick }) => {
  const intl = useIntl();

  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'maintenance.stieNo' }),
      dataIndex: 'index',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'remoteMaintenance.detail.serverName' }),
      dataIndex: 'hostName',
      key: 'hostName',
      hideInSearch: true,
      search: {
        transform: (value) => ({ hostName: value }),
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteMaintenance.detail.onlineStatus' }),
      dataIndex: 'onlineState',
      key: 'onlineState',
      valueEnum: {
        '1': {
          text: intl.formatMessage({ id: 'remoteMaintenance.detail.online' }),
          status: 'Success',
        },
        '0': {
          text: intl.formatMessage({ id: 'remoteMaintenance.detail.offline' }),
          status: 'Error',
        },
      },
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteMaintenance.detail.updateTime' }),
      dataIndex: 'updatedTime',
      key: 'updatedTime',
      valueType: 'dateTime',
      hideInSearch: true,
      search: {
        transform: (value) => {
          return {
            configStartTime: value[0],
            configEndTime: value[1],
          };
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteMaintenance.detail.alarmStatus' }),
      dataIndex: 'alarmStatus',
      key: 'alarmStatus',
      valueEnum: {
        '0': {
          text: intl.formatMessage({ id: 'remoteMaintenance.detail.normal' }),
          status: 'Success',
        },
        '1': {
          text: intl.formatMessage({ id: 'remoteMaintenance.detail.alarm' }),
          status: 'Error',
        },
      },
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteMaintenance.detail.operation' }),
      key: 'operation',
      hideInSearch: true,
      render: (_, record) => (
        <Space>
          <a onClick={() => onDetailsClick(record.id)}>
            {intl.formatMessage({ id: 'remoteMaintenance.detail.details' })}
          </a>
          <Access perm={'remote:ota'} key="ota">
            <Link
              to={`/remoteUpgrade/remoteMaintenance/ota?stationid=${record?.id}`}
              onClick={() => {
                sessionStorage.setItem(
                  'EmsComponentParams',
                  JSON.stringify({
                    stationId: stationId,
                    serverId: record?.id,
                  }),
                );
              }}
              key="ota"
            >
              {intl.formatMessage({ id: 'maintenance.ota' })}
            </Link>
          </Access>
        </Space>
      ),
    },
  ];

  return (
    <ProTable
      className={styles.remoteTable}
      rowKey="id"
      columns={columns}
      pagination={{
        pageSize: 10,
        showSizeChanger: true,
      }}
      request={async (params) => {
        const { current, pageSize } = params;
        const response = await monitorServerControllerServerPage({
          current: current ?? 1,
          pageSize: pageSize ?? 10,
          stationId,
        });
        return {
          data: response.data?.records ?? [],
          success: response.success ?? false,
          total: response.data?.total ?? 0,
        };
      }}
      search={false}
      style={{ paddingLeft: 30, paddingRight: 30 }}
    />
  );
};

const Detail: React.FC = () => {
  const intl = useIntl();
  const location = useLocation();
  const { stationid } = parse(location.search.slice(1)) as { stationid: string };
  const [activeKey, setActiveKey] = useState('1');
  const [selectedServerId, setSelectedServerId] = useState<string | null>(null);
  const [refreshKey, setRefreshKey] = useState(0);

  const handleDetailsClick = (serverId: number) => {
    setSelectedServerId(serverId.toString());
  };

  const handleTabChange = (key: string) => {
    setActiveKey(key);
    setRefreshKey((prev) => prev + 1);
  };

  const renderStatusContent = () => {
    if (selectedServerId) {
      return (
        <BaseInfo key={refreshKey} id={selectedServerId} onBack={() => setSelectedServerId(null)} />
      );
    }
    return (
      <StatusList
        key={refreshKey}
        stationId={parseInt(stationid, 10)}
        onDetailsClick={handleDetailsClick}
      />
    );
  };

  const items = [
    {
      key: '1',
      label: intl.formatMessage({ id: 'remoteMaintenance.detail.statusList' }),
      children: renderStatusContent(),
    },
    {
      key: '2',
      label: intl.formatMessage({ id: 'remoteMaintenance.detail.alarmConfig' }),
      children: <AlarmConfig key={refreshKey} id={stationid} />,
    },
    {
      key: '3',
      label: intl.formatMessage({ id: 'remoteMaintenance.detail.alarmHistory' }),
      children: <AlarmHistory key={refreshKey} id={stationid} />,
    },
    {
      key: '4',
      label: intl.formatMessage({ id: 'remoteMaintenance.detail.ota' }),
      children: <PackageMang />,
    },
  ];

  return (
    <div className={styles.detailContainer}>
      <Tabs activeKey={activeKey} items={items} onChange={handleTabChange} />
    </div>
  );
};

export default Detail;
